package com.happycat.configuration;

import com.happycat.base.exception.RestApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理，优先级最高(最外层)
 */
@Slf4j
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {


    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Object handleException(Exception e) {
        log.error("系统内部异常，异常信息：", e);
        Map<String, Object> errMap = new HashMap<>();
        errMap.put("code", 500);
        errMap.put("message", "系统异常");
        return errMap ;
    }


    @ExceptionHandler(value = RestApiException.class)
    public Object handleApiException(RestApiException e) {
        return e.getResponse();
    }

    //request body missing
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public Object handleRequestMissingException(HttpMessageNotReadableException e) {
        Map<String, Object> errMap = new HashMap<>();
        log.error(e.getMessage());
        errMap.put("code", -1);
        errMap.put("message", "参数错误");
        return errMap ;
    }

    //request parameter missing
    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    public Object handleRequestMissingException(MissingServletRequestParameterException e) {
        Map<String, Object> errMap = new HashMap<>();
        log.error("请求参数["+e.getParameterName()+"]不能为空");
        errMap.put("code", -1);
        errMap.put("message", "参数错误");
        return errMap ;
    }

    //参数校验异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Object handleValidationException(MethodArgumentNotValidException e) {
        StringBuilder sb = new StringBuilder("参数错误：[");
        for (ObjectError item :  e.getBindingResult().getAllErrors()) {
            sb.append(item.getDefaultMessage()).append(',');
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append(']');

        log.error(e.getMessage());

        Map<String, Object> errMap = new HashMap<>();
        errMap.put("code", -1);
        errMap.put("message", sb.toString());
        return errMap ;
    }

    //参数校验异常
    @ExceptionHandler(value = BindException.class)
    public Object handleValidationException(BindException e) {
        StringBuilder sb = new StringBuilder("参数错误：[");
        for (ObjectError item :  e.getAllErrors()) {
            sb.append(item.getDefaultMessage()).append(',');
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append(']');

        log.error(sb.toString());

        Map<String, Object> errMap = new HashMap<>();
        errMap.put("code", -1);
        errMap.put("message", sb.toString());
        return errMap ;
    }

//    @ExceptionHandler(value = LimitAccessException.class)
//    @ResponseStatus(HttpStatus.TOO_MANY_REQUESTS)
//    public Object handleLimitAccessException(LimitAccessException e) {
//        log.warn(e.getMessage());
//        return ApiResponse.TOO_MANY_REQUESTS.toMap();
//    }
//
//    @ExceptionHandler(value = UnauthorizedException.class)
//    @ResponseStatus(HttpStatus.FORBIDDEN)
//    public void handleUnauthorizedException(Exception e) {
//        log.error("权限不足，{}", e.getMessage());
//    }
//
//    @ExceptionHandler(value = AuthenticationException.class)
//    @ResponseStatus(HttpStatus.FORBIDDEN)
//    public void handleAuthenticationException(Exception e) {
//        log.error("Token无效，{}", e.getMessage());
//    }
//


}
